﻿using System;

using AMC.SubstitutionCache.Rendering;

using Orchard.ContentManagement;
using Orchard.DisplayManagement;

namespace AMC.SubstitutionCache.Services
{
    /// <summary>
    /// information about the cached item and information on how to replace it during re-render.
    /// </summary>
    public class SubstitutionContext : SubstitutionShapeRenderingInfo
    {
        public SubstitutionContext(IShape shape)
            : this(
                shape.Metadata.Type,
                ((dynamic)shape).TemplateName as string,
                ((dynamic)shape).ContentPart as ContentPart,
                shape.Metadata.DisplayType,
                shape.GetGroupId()) { }

        public SubstitutionContext(
            string shapeType,
            string templateName,
            ContentPart part,
            string displayType,
            string groupId)
            : base(
                (part == null ? typeof(ContentPart) : part.GetType()),
                ShapeHelper.GetShapeType(shapeType, templateName),
                groupId)
        {
            if (part != null)
            {
                ContentId = part.Id;

                if (ContentId == 0) // TODO: other full cache scenarios?
                    ContentPart = part;
            }

            DisplayType = displayType;
        }

        public int ContentId { get; set; }

        public ContentPart ContentPart { get; set; }

        public string DisplayType { get; set; }

        public Guid? RequestId { get; set; }

        public string Key
        {
            get
            {
                return string.Format(
                    "Id:{0},PartType:{1},DisplayType:{2},GroupId:{3},ShapeType:{4}",
                    ContentId,
                    ContentPartType.Name,
                    DisplayType,
                    GroupId,
                    ShapeType);
            }
        }
    }
}